package com.ruoyi.syf.task.config;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.ruoyi.syf.domain.RiskCheckTask;
import com.ruoyi.syf.service.IRiskCheckTaskService;
import com.ruoyi.syf.handler.task.TaskFactory;
import com.ruoyi.syf.task.enttity.ScheduleSetting;
import com.ruoyi.syf.task.service.ScheduleSettingService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * 定时任务预热
 */
@Slf4j
@Service
public class SysJobRunner implements CommandLineRunner {

    @Resource
    private CronTaskRegistrar cronTaskRegistrar;

    @Resource
    private TaskFactory taskFactory;

    @Resource
    private ScheduleSettingService scheduleSettingService;

    @Resource
    private IRiskCheckTaskService riskCheckTaskService;

    @Override
    public void run(String... args) {
        try {
            checkJob();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
    }

    /**
     * 排查任务
     */
    public void checkJob() throws IllegalAccessException {
        List<ScheduleSetting> jobList = scheduleSettingService.list(new LambdaQueryWrapper<ScheduleSetting>()
                .eq(ScheduleSetting::getBeanName,"CheckTask")
                .eq(ScheduleSetting::getMethodName,"taskSaveRecord")
                .eq(ScheduleSetting::getStatus, true));
        if (CollectionUtils.isNotEmpty(jobList)) {
            for (ScheduleSetting job : jobList) {
                String taskId = job.getMethodParams();
                RiskCheckTask task = riskCheckTaskService.getById(taskId);
                if (task.getNextActualStartTime().getTime() < System.currentTimeMillis()) {
                    //计算离当前时间最近一条排查任务的开始时间
                    Date lastBeginTime = taskFactory.getRecentBeginTime(
                            task.getCycleType(),
                            task.getNextActualStartTime(),
                            task.getCycle(),
                            task.getCycleUnit());
                    task.setNextActualStartTime(lastBeginTime);
                    riskCheckTaskService.updateById(task);
                }
                SchedulingRunnable schedulingRunnable = new SchedulingRunnable(job.getBeanName(), job.getMethodName(), taskId);
                cronTaskRegistrar.addCronTask(schedulingRunnable, job.getCron());
            }
            log.info("加载{}个隐患排查定时任务",jobList.size());
        }
        log.info("隐患排查定时任务已加载完毕...");
    }


}
